package com.lanlian.utillib;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;

public class MaxTextLengthFilter implements InputFilter {

    private int mMaxLength;
    private Context mContext;

    public MaxTextLengthFilter(int max, Context context) {
        this.mMaxLength = max;
        this.mContext = context;
    }

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int keep = mMaxLength - (dest.length() - (dend - dstart));
        if (keep < (end - start)) {
            ToastUtils.show(mContext, "输入不能超过" + mMaxLength + "字");
        }
        if (keep <= 0) {
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            return source.subSequence(start, start + keep);
        }
    }
}